<template>
    <div>
        <div class="whole_top">
            <el-row :gutter="10">
                <el-col :span="18">
                    <el-input v-model="input" style="width: 240px" placeholder="参数名" clearable />
                    <el-button style="margin-left: 20px;" @click="handleQuery">查询</el-button>
                    <el-button type="success" @click="handleAdd">新增</el-button>
                    <el-button type="danger"  :disabled="currentRow.length===0" @click="handleBatchDelete">批量删除</el-button>
                </el-col>
            </el-row>
        </div>
        <div class="whole_table">
            <el-table border :data="tableData" @selection-change="handleSelectionChange" style="width: 100%">
                <el-table-column type="selection" width="55" />
                <el-table-column property="groupCode" label="组编码" width="250">
                </el-table-column>
                <el-table-column property="groupName" label="组名称" width="250" />
                <el-table-column property="groupAddress" label="组地址" width="250" />
                <el-table-column property="remark" label="备注" width="250" />
                <el-table-column label="操作">
                    <template #default="scope">
                        <el-button type="primary" @click="handleEdit(scope.row)">修改</el-button>
                        <el-button type="danger" @click="handleDelete(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <page :query="query" :total="total" @size-change="sChange" @page-change="pChange"></page>
        <!-- 弹窗 -->
        <el-dialog :title="title" v-model="dialogVisible" width="50%">
            <el-form ref="ruleFormRef" :model="from" :rules="rules" label-width="80px">
                <el-form-item label="组编码" prop="groupCode">
                    <el-input v-model="from.groupCode" disabled  placeholder="组编码">
                        <template #append >
                            <el-button @click="Shengcheng" type="text">生成</el-button>
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item label="组名称" prop="groupName">
                    <el-input v-model="from.groupName" placeholder="组名称" clearable />
                </el-form-item>
                <el-form-item label="管理员" prop="managerName">
                    <el-input v-model="from.managerName" placeholder="管理员" clearable />
                </el-form-item>
                <el-form-item label="组地址" prop="groupAddress">
                    <el-input v-model="from.groupAddress" placeholder="组地址" clearable />
                </el-form-item>
                <el-form-item label="是否可用" prop="enabled">
                    <el-radio-group v-model="from.enabled" placeholder="请选择">
                        <el-radio :label="1">可用</el-radio>
                        <el-radio :label="2">不可用</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="from.remark" placeholder="备注" clearable />
                </el-form-item>
                <el-form-item>

                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitForm(ruleFormRef)">确定</el-button>

                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import { getEquipmentGroup, addSave,getGroupCode,editSave,editDetail,deleteGroup } from '@/api/equipmentgroup'
import page from '@/components/page.vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { id } from 'element-plus/es/locale'

const input = ref('')
// const radio = ref(1)
const query = reactive({
    t: new Date().getTime(),
    page: 1,
    limit: 10,
    key: null,
})
// 分页
const total = ref(0)
// 当前行
const currentRow = ref([])
// 批量删除
const disabled = ref(false)
// 弹窗
const dialogVisible = ref(false)
const title = ref()
// 表单
const ruleFormRef = ref<FormInstance>()
const from = reactive<RuleForm>({
    groupCode: '',
    groupName: '',
    managerName: '',
    groupAddress: '',
    enabled: 1,
    remark: '',
})
let id =ref(0)
const rules = reactive<FormRules<RuleForm>>({
    groupCode: [
        { required: true, message: '组编号不能为空', trigger: 'blur' },
    ],
    groupName: [
        { required: true, message: '组名称不能为空', trigger: 'blur' },
    ],
    managerName: [
        { required: true, message: '管理员不能为空', trigger: 'blur' },
    ],
    groupAddress: [
        { required: true, message: '组地址不能为空', trigger: 'blur' },
    ],
    enabled: [
        { required: true, message: '请选择是否可用', trigger: 'change' },
    ],
    remark: [
        { required: true, message: '备注不能为空', trigger: 'blur' },
    ],
})

// const from=reactive({
//   date: '',
//   name: '',
//   address: ''
// })
const tableData = ref([])


// 函数：=========================================
function handleSelectionChange(val: any){
    currentRow.value = val
    console.log(val, 'currentRow');
    
}
// 调用数据
function getList() {
    getEquipmentGroup(query).then(res => {
        console.log(res, 'res');
        tableData.value = res.page.list
        total.value = res.page.totalCount
    })
}
// 查询
function handleQuery() {
    query.page=1
    query.key = input.value
    getList()
}

// 新增
function handleAdd() {
    dialogVisible.value = true
    title.value = '新增'
    // 先重置表单
    nextTick(() => {
        ruleFormRef.value?.resetFields()
    })
}
// 新增确定
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            if(title.value === '新增'){
                addSave(from).then(res => {
                    console.log(res, '新增');
                    ElMessage({
                        message: "新增成功",
                        type: 'success',
                    })    
                    dialogVisible.value = false
                    ruleFormRef.value?.resetFields()
                    getList()
                })
            }else{
                // console.log('修改')
                editSave({
                    id:id.value,
                    ...from
                }).then(res => {
                    console.log(res, '修改');
                    ElMessage({
                        message: "修改成功",
                        type: 'success',
                    })    
                    dialogVisible.value = false
                    getList()
            })
            } 
                
            // console.log('submit!')
        } else {
            console.log('error submit!', fields)
        }
    })
}
// 生成组编码
function Shengcheng() {
    getGroupCode().then(res => {
        console.log(res, 'getGroupCode');
        from.groupCode = res.equipmentGroupSequence
    })
}
// 修改
function handleEdit(row: any) {
    dialogVisible.value = true
    title.value = '修改'
    editDetail(row.id).then(res => {
        console.log(res, 'editDetail');
        id.value = row.id
        from.groupCode = row.groupCode
        from.groupName = row.groupName
        from.managerName = row.managerName
        from.groupAddress = row.groupAddress
        from.enabled = row.enabled
        from.remark = row.remark
    })
}
// 删除
function handleDelete(row: any) {
    ElMessageBox.confirm(`确认删除id=${row.id}该记录吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        console.log(row, '删除');
        deleteGroup([row.id]).then(res => {
            console.log(res, '删除');
            ElMessage({
                message: "删除成功",
                type: 'success',
            })    
            getList()
        })
    }).catch(() => {
        console.log('取消删除')
    })
}
// 批量删除
function handleBatchDelete() {
    if (currentRow.value.length === 0) {
        ElMessage({
            message: "请选择要删除的行",
            type: 'warning',
        })
        return
    }
    const selectedIds = currentRow.value.map(item => item.id); 
    ElMessageBox.confirm(`确认删除id= [${selectedIds}] 条记录吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        deleteGroup(selectedIds).then(res => {
            console.log(res, '批量删除');
            ElMessage({
                message: "批量删除成功",
                type: 'success',
            })    
            getList()
            currentRow.value = []; // Clear selection after deletion
        }).catch(error => {
            console.error('批量删除失败:', error);
            ElMessage({
                message: "批量删除失败",
                type: 'error',
            })
        })
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '已取消删除'
        })
    })
}

// 生命周期调用
onMounted(() => {
    getList()
})

// 分页
// 切换条数
const sChange = (val: number) => {
    console.log(`切换为每页：${val}条`);
    query.limit = val
    getList()
}
// 切换页数
const pChange = (val: number) => {
    console.log(`第${val}页`);
    query.page = val
    getList()
}

</script>

<style scoped>
.whole_table {
    margin-top: 20px;
}
</style>